package cn.book.dao;

import java.sql.*;

public class BaseDao {
    private ResultSet rs = null;
    private PreparedStatement pst = null;
    private Connection conn = null;
    private static final String URL = "jdbc:mysql://localhost:3306/bookshop";
    private static final String USER = "root";
    private static final String PASSWORD = "admin";

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public ResultSet query(Object param[], String sql) {
        try {
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            pst = conn.prepareStatement(sql);
            if (param != null) {
                for (int i = 0; i < param.length; i++) {
                    pst.setObject(i + 1, param[i]);
                }
            }
            rs = pst.executeQuery();
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int update(Object param[], String sql) {
        int i = 0;
        try {
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            pst = conn.prepareStatement(sql);
            if (param != null) {
                for (int a = 0; a < param.length; a++) {
                    pst.setObject(a + 1, param[a]);
                }
            }
            i = pst.executeUpdate();
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public void close(){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs = null;
        }

        if(pst!=null){
            try {
                pst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            pst = null;
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            conn = null;
        }

    }
}

